package wang.xinqiu.mysqlcontrol.data

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import java.io.File
import java.io.FileWriter
import java.text.SimpleDateFormat
import java.util.*
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.io.FileOutputStream

class DataExporter {
    
    fun exportToFile(
        context: Context,
        queryResult: QueryResult,
        format: String,
        fileName: String? = null,
        customPath: String? = null
    ): Result<String> {
        return try {
            val file = if (customPath != null) {
                createCustomExportFile(customPath, format, fileName)
            } else {
                createExportFile(context, format, fileName)
            }
            
            // 检查写入权限
            if (!canWriteToPath(file.parentFile)) {
                return Result.failure(Exception("没有写入权限: ${file.parentFile?.absolutePath}"))
            }
            
            when (format.uppercase()) {
                "CSV" -> {
                    val content = exportToCSV(queryResult)
                    FileWriter(file).use { writer ->
                        writer.write(content)
                    }
                }
                "JSON" -> {
                    val content = exportToJSON(queryResult)
                    FileWriter(file).use { writer ->
                        writer.write(content)
                    }
                }
                "XML" -> {
                    val content = exportToXML(queryResult)
                    FileWriter(file).use { writer ->
                        writer.write(content)
                    }
                }
                "EXCEL" -> {
                    exportToExcel(queryResult, file)
                }
                else -> return Result.failure(Exception("不支持的格式: $format"))
            }
            
            Result.success(file.absolutePath)
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
    
    fun exportToUri(
        context: Context,
        queryResult: QueryResult,
        format: String,
        uri: Uri
    ): Result<String> {
        return try {
            when (format.uppercase()) {
                "EXCEL" -> {
                    context.contentResolver.openOutputStream(uri)?.use { outputStream ->
                        val workbook = createExcelWorkbook(queryResult)
                        workbook.write(outputStream)
                        workbook.close()
                    } ?: return Result.failure(Exception("无法打开输出流"))
                }
                else -> {
                    val content = when (format.uppercase()) {
                        "CSV" -> exportToCSV(queryResult)
                        "JSON" -> exportToJSON(queryResult)
                        "XML" -> exportToXML(queryResult)
                        else -> return Result.failure(Exception("不支持的格式: $format"))
                    }
                    
                    context.contentResolver.openOutputStream(uri)?.use { outputStream ->
                        outputStream.write(content.toByteArray())
                    } ?: return Result.failure(Exception("无法打开输出流"))
                }
            }
            
            Result.success(uri.toString())
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
    
    private fun createCustomExportFile(customPath: String, format: String, fileName: String?): File {
        val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val finalFileName = fileName ?: "mysql_export_$timestamp"
        val extension = when (format.uppercase()) {
            "CSV" -> "csv"
            "JSON" -> "json"
            "XML" -> "xml"
            "EXCEL" -> "xlsx"
            else -> "txt"
        }
        
        val exportDir = File(customPath)
        if (!exportDir.exists()) {
            exportDir.mkdirs()
        }
        
        return File(exportDir, "$finalFileName.$extension")
    }
    
    private fun createExportFile(context: Context, format: String, fileName: String?): File {
        val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val finalFileName = fileName ?: "mysql_export_$timestamp"
        val extension = when (format.uppercase()) {
            "CSV" -> "csv"
            "JSON" -> "json"
            "XML" -> "xml"
            "EXCEL" -> "xlsx"
            else -> "txt"
        }
        
        val exportDir = File(context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), "exports")
        if (!exportDir.exists()) {
            exportDir.mkdirs()
        }
        
        return File(exportDir, "$finalFileName.$extension")
    }
    
    private fun exportToExcel(queryResult: QueryResult, file: File) {
        val workbook = createExcelWorkbook(queryResult)
        FileOutputStream(file).use { fileOut ->
            workbook.write(fileOut)
        }
        workbook.close()
    }
    
    private fun createExcelWorkbook(queryResult: QueryResult): Workbook {
        val workbook: Workbook = XSSFWorkbook()
        val sheet = workbook.createSheet("Query Result")
        
        // 创建表头样式
        val headerStyle = workbook.createCellStyle()
        val headerFont = workbook.createFont()
        headerFont.bold = true
        headerStyle.setFont(headerFont)
        
        // 创建表头行
        val headerRow = sheet.createRow(0)
        queryResult.columns.forEachIndexed { index, columnName ->
            val cell = headerRow.createCell(index)
            cell.setCellValue(columnName)
            cell.cellStyle = headerStyle
        }
        
        // 创建数据行
        queryResult.rows.forEachIndexed { rowIndex, row ->
            val dataRow = sheet.createRow(rowIndex + 1)
            row.forEachIndexed { colIndex, cellValue ->
                val cell = dataRow.createCell(colIndex)
                cell.setCellValue(cellValue)
            }
        }
        
        // 基于内容长度手动计算列宽
        queryResult.columns.indices.forEach { colIndex ->
            var maxLength = queryResult.columns[colIndex].length
            
            // 检查该列所有数据的最大长度
            queryResult.rows.forEach { row ->
                if (colIndex < row.size) {
                    maxLength = maxOf(maxLength, row[colIndex].length)
                }
            }
            
            // 设置列宽（Excel 单位：1/256 字符宽度）
            val width = minOf(maxLength * 256 + 512, 15000) // 限制最大宽度
            sheet.setColumnWidth(colIndex, width)
        }
        
        return workbook
    }
    
    fun canWriteToPath(directory: File?): Boolean {
        return try {
            directory?.let {
                it.exists() && it.canWrite() && it.isDirectory
            } ?: false
        } catch (e: Exception) {
            false
        }
    }
    
    fun getAvailableExportPaths(context: Context): List<ExportPath> {
        val paths = mutableListOf<ExportPath>()
        
        // 应用私有目录（总是可写）
        val appDir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
        if (appDir != null) {
            paths.add(ExportPath(
                path = appDir.absolutePath,
                displayName = "应用文档目录",
                isWritable = true,
                description = "应用私有存储，无需权限"
            ))
        }
        
        // 公共下载目录
        val downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
        paths.add(ExportPath(
            path = downloadDir.absolutePath,
            displayName = "下载目录",
            isWritable = canWriteToPath(downloadDir),
            description = "系统下载文件夹"
        ))
        
        // 公共文档目录
        val documentsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
        paths.add(ExportPath(
            path = documentsDir.absolutePath,
            displayName = "文档目录",
            isWritable = canWriteToPath(documentsDir),
            description = "系统文档文件夹"
        ))
        
        // 外部存储根目录
        val externalDir = Environment.getExternalStorageDirectory()
        paths.add(ExportPath(
            path = externalDir.absolutePath,
            displayName = "外部存储根目录",
            isWritable = canWriteToPath(externalDir),
            description = "需要存储权限"
        ))
        
        return paths
    }
    
    fun createDocumentIntent(format: String): Intent {
        val mimeType = when (format.uppercase()) {
            "CSV" -> "text/csv"
            "JSON" -> "application/json"
            "XML" -> "text/xml"
            "EXCEL" -> "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            else -> "text/plain"
        }
        
        val extension = when (format.uppercase()) {
            "CSV" -> "csv"
            "JSON" -> "json"
            "XML" -> "xml"
            "EXCEL" -> "xlsx"
            else -> "txt"
        }
        
        val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val fileName = "mysql_export_$timestamp.$extension"
        
        return Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = mimeType
            putExtra(Intent.EXTRA_TITLE, fileName)
        }
    }
    
    fun exportToCSV(queryResult: QueryResult): String {
        val csv = StringBuilder()
        
        // 添加列标题
        csv.append(queryResult.columns.joinToString(",") { "\"$it\"" })
        csv.append("\n")
        
        // 添加数据行
        queryResult.rows.forEach { row ->
            csv.append(row.joinToString(",") { "\"${it.replace("\"", "\"\"")}\"" })
            csv.append("\n")
        }
        
        return csv.toString()
    }
    
    fun exportToJSON(queryResult: QueryResult): String {
        val json = StringBuilder()
        json.append("[\n")
        
        queryResult.rows.forEachIndexed { index, row ->
            json.append("  {\n")
            queryResult.columns.forEachIndexed { colIndex, column ->
                val value = row.getOrNull(colIndex) ?: ""
                json.append("    \"$column\": \"${value.replace("\"", "\\\"")}\"\n")
                if (colIndex < queryResult.columns.size - 1) json.append(",")
            }
            json.append("  }")
            if (index < queryResult.rows.size - 1) json.append(",")
            json.append("\n")
        }
        
        json.append("]")
        return json.toString()
    }
    
    fun exportToXML(queryResult: QueryResult): String {
        val xml = StringBuilder()
        xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
        xml.append("<data>\n")
        
        queryResult.rows.forEach { row ->
            xml.append("  <row>\n")
            queryResult.columns.forEachIndexed { colIndex, column ->
                val value = row.getOrNull(colIndex) ?: ""
                xml.append("    <$column>${value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")}</$column>\n")
            }
            xml.append("  </row>\n")
        }
        
        xml.append("</data>")
        return xml.toString()
    }
    
    fun getExportDirectory(context: Context): File {
        return File(context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), "exports")
    }
}

data class ExportPath(
    val path: String,
    val displayName: String,
    val isWritable: Boolean,
    val description: String
)